<?php

namespace App\Repositories\WebSocket;

use Illuminate\Http\Request;
use SwooleTW\Http\Websocket\SocketIO\WebsocketHandler;

class SocketHandler extends WebsocketHandler
{
    /**
     * 客户端Fd管理
     *
     * @var ClientManager
     */
    private $clientManager;

    public function __construct()
    {
        $this->clientManager = new ClientManager();
    }
    
    /**
     * 连接成功方法
     *
     * @param int $fd 客户端ID
     * @param Request $request
     * @return bool
     */
    public function onOpen($fd, Request $request)
    {
        $userId = $request->get('uid');

        // 绑定用户与fd该功能了
        $this->clientManager->bindFdToUser($fd, $userId);
        $this->clientManager->bindUserIdToFds($fd, $userId);


        return true;
    }

    /**
     * Websocket 客户端断开事件
     *
     * @param int $fd 客户端ID
     * @param int $reactorId swoole 线程ID
     * @return bool|void
     */
    public function onClose($fd, $reactorId)
    {
        // 清除用户绑定信息
        $this->clientManager->deleteFd($fd);

        return true;
    }
}
